import time
from transitions import Machine


class ControlPanel:
    states = ['input', 'locked', 'function']

    def __init__(self,password):
        self.machine = Machine(model=self, states=ControlPanel.states, initial='input')
        self.password = password  # 设置的密码
        self.input_buffer = ""  # 用于存储输入的密码
        self.failed_attempts = 0  # 记录密码输入失败次数
        self.locked_time = time.localtime().tm_sec  # 记录锁定时间

        self.machine.add_transition(trigger='input', source='input', dest='input',conditions=['check_password_length'], after='check_password')
        self.machine.add_transition(trigger='lock', source='input', dest='locked')
        self.machine.add_transition(trigger='unlock', source='locked', dest='input', conditions=['locktime_check'],after='reset_failed_attempts')
        self.machine.add_transition(trigger='correct',source= 'input',dest='function')

    def check_password_length(self):
        return len(self.input_buffer) ==4

    def check_password(self):
        if self.input_buffer == self.password:
            self.correct()
        else:
            self.failed_attempts += 1
            self.input_buffer=''
            if self.failed_attempts >= 3:
                self.lock()
                self.locked_time=time.localtime().tm_sec+3
    def reset_failed_attempts(self):
        self.failed_attempts = 0
        self.input_buffer = ""
    def input_digit(self, digit):
        self.input_buffer += digit
    def locktime_check(self):
        return self.locked_time-time.localtime().tm_sec<0
    def run(self):
        while True:
            if self.state=="input":
                print("请输入第 ",len(self.input_buffer)+1,"位密码")
                self.input_digit(input())
                self.input()
            if self.state=="function":
                print("进入功能面板")
                break
            if self.state=="locked":
                time.sleep(1)
                print("还剩", self.locked_time - time.localtime().tm_sec)
                self.unlock()

control_panel = ControlPanel("1234")
control_panel.run()